package event.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


class Database {
	private Connection connection;

	private String host;
	private String user;
	private String password;

	public Database() {
		this.host = "jdbc:mysql://snejk.dsek.lth.se/dsek";
		this.user = "narwhal";
		this.password = "tastatur";
		connectToDb();
	}
	
	private boolean connectToDb() {
		boolean connected = false;
		try {
			if (connection == null || connection.isClosed()) {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				connection = DriverManager.getConnection(host, user, password);
			}
			if (connection != null)
				connected = !connection.isClosed();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return connected;
	}


	public synchronized ResultSet query(String query) {
		try {
			Statement stmt = connection.createStatement();
			return stmt.executeQuery(query);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public synchronized int update(String query) {
		try {
			Statement stmt = connection.createStatement();
			return stmt.executeUpdate(query);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	
	public void close() {
		try {
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
